package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.DishDTO;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional  //由于是对两张表进行了操作，所以要开启事务
    public void saveDish(DishDTO dishDTO) {
        //保存菜品
        super.save(dishDTO);
        //保存口味
        //1.因为口味存储的是list，所以要循环插入
        /*for (DishFlavor list : dishDTO.getDishFlavorLists()) {
            list.setDishId(dishDTO.getId());
        }*/
        addDishFlavorList(dishDTO);

    }

    @Override
    public DishDTO queryDishInfo(String id) {
        //1. 查询菜品基本信息
        Dish dish = super.getById(id);
        //2. 根据菜品ID查询口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavorLists = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        //3.封装数据到DishDTO中
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish,dishDTO);
        dishDTO.setFlavors(dishFlavorLists);
        return dishDTO;
    }

    @Override
    @Transactional
    public void updateDishInfoById(DishDTO dishDTO) {
        //1.直接修改菜品表
        super.updateById(dishDTO);
        //2.物理删除所有对应菜品的所有口味
        dishFlavorService.deleteByDishId(dishDTO.getId());
        //3.重新添加口味表
        addDishFlavorList(dishDTO);
    }

    /**
     * <p>Description: 循环添加口味信息表</p>
     *
     * @author liuyiming
     * @date 2022-10-12 10:36
     * @version 1.0.0
     */
    private void addDishFlavorList(DishDTO dishDTO){
        //获取菜品口味
        List<DishFlavor> dishFlavorLists = dishDTO.getFlavors();
        //因为传的菜品口味中有个字段是菜品id，是没有进行赋值的
        //所以用Stream流对口味中的菜品id进行赋值
        dishFlavorLists = dishFlavorLists.stream().map(item -> {
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());
        //保存口味表
        dishFlavorService.saveBatch(dishFlavorLists);
    }
}
